//
//  User.swift
//  hello
//
//  Created by 赵康 on 2024/11/11.
//

import Vapor
import Fluent

final class User: Model, Content, @unchecked Sendable {
	static var schema: String { SchemaEnum.users.rawValue }
	
	@ID(key: .id)
	var id: UUID?
	
	@Field(key: FieldKeys.name)
	var name: String
	
	@Field(key: FieldKeys.email)
	var email: String
	
	@Field(key: FieldKeys.password)
	var password: String
	
	@OptionalField(key: FieldKeys.avatar)
	var avatar: String?
	
	@Field(key: FieldKeys.phone)
	var phone: String
	
	@OptionalField(key: FieldKeys.bio)
	var bio: String?
	
	@Field(key: FieldKeys.isDeleted)
	var isDeleted: Bool
	
	@Timestamp(key: FieldKeys.createdAt, on: .create)
	var createdAt: Date?
	
	@Timestamp(key: FieldKeys.updatedAt, on: .update)
	var updatedAt: Date?
	
	@Field(key: FieldKeys.isEmailVerified)
	var isEmailVerified: Bool
	
	@Field(key: FieldKeys.isPhoneVerified)
	var isPhoneVerified: Bool
	
	@Field(key: FieldKeys.isSubscribed)
	var isSubscribed: Bool
	
	@Field(key: FieldKeys.currentStreak)
  var currentStreak: Int // 当前连续学习天数
  
  @Field(key: FieldKeys.dailyGoal)
  var dailyGoal: Double // 每日学习目标（秒）
  
  @Field(key: FieldKeys.points)
  var points: Int // 用户积分
  
  @OptionalField(key: FieldKeys.lastPointsAwardedDate)
  var lastPointsAwardedDate: Date? // 上次奖励积分的日期
  
  @Field(key: FieldKeys.totalCheckIns)
  var totalCheckIns: Int // 总打卡天数
  
  @Field(key: FieldKeys.lastMilestoneAwarded)
  var lastMilestoneAwarded: Int // 上次获得里程碑奖励的打卡天数
	
  @Field(key: FieldKeys.termsAccepted)
  var termsAccepted: Bool // 是否接受条款
	
	@Field(key: FieldKeys.termsAcceptedAt)
	var termsAcceptedAt: Date? // 条款接受日期
	
	@Field(key: FieldKeys.termsVersion)
	var termsVersion: String? // 条款版本
  
  @OptionalField(key: FieldKeys.appleUserID)
  var appleUserID: String? // Apple用户唯一标识
	
	@Children(for: \.$user)
	var favorites: [Favorite]
	
	@Children(for: \.$user)
	var histories: [History]
	
	@Children(for: \.$user)
	var notes: [Note]
	
  @Children(for: \.$user)
  var noteTags: [NoteTag]
  
  // 多尺寸头像URLs，不存储在数据库中
  var avatarUrls: [String: String]?
  
	init() { }
	
	init(
		id: UUID? = nil,
		name: String,
		email: String,
		password: String,
		avatar: String? = nil,
		phone: String = "",
		bio: String? = nil,
		isDeleted: Bool = false,
		isEmailVerified: Bool = false,
		isPhoneVerified: Bool = false,
		isSubscribed: Bool = false,
		currentStreak: Int = 0,
    dailyGoal: Double = 600, // 默认10分钟
    points: Int = 0,
    lastPointsAwardedDate: Date? = nil,
    totalCheckIns: Int = 0,
    lastMilestoneAwarded: Int = 0,
    termsAccepted: Bool = false,
    termsAcceptedAt: Date? = nil,
    termsVersion: String? = nil,
    appleUserID: String? = nil
	) {
		self.id = id
		self.name = name
		self.email = email
		self.password = password
		self.avatar = avatar
		self.phone = phone
		self.bio = bio
		self.isDeleted = isDeleted
		self.createdAt = nil
		self.updatedAt = nil
		self.isEmailVerified = isEmailVerified
		self.isPhoneVerified = isPhoneVerified
		self.isSubscribed = isSubscribed
		self.currentStreak = currentStreak
    self.dailyGoal = dailyGoal
    self.points = points
    self.lastPointsAwardedDate = lastPointsAwardedDate
    self.totalCheckIns = totalCheckIns
    self.lastMilestoneAwarded = lastMilestoneAwarded
    self.termsAccepted = termsAccepted
    self.termsAcceptedAt = termsAcceptedAt
    self.termsVersion = termsVersion
    self.appleUserID = appleUserID
    self.avatarUrls = nil
	}

  
  // 邮箱+密码注册
  struct EmailPasswordRegister: Content {
    var email: String
    var password: String
    var agreedToTerms: Bool
  }
  
  // 默认登录方式改成 name/email/phone + password 登录
  struct Login: Content {
    var identifier: String
    var password: String
    var agreedToTerms: Bool
  }
  
  // 邮箱验证码登录
  struct EmailCodeLogin: Content {
    var email: String
    var code: String
    var agreedToTerms: Bool
  }
  
  // 手机验证码登录
  struct PhoneCodeLogin: Content {
    var phone: String
    var code: String
    var agreedToTerms: Bool
  }
  
  struct Update: Content {
    var name: String?
    var email: String?
    var password: String?
    var phone: String?
    var avatar: String?
    var bio: String?
    var isEmailVerified: Bool?
    var isPhoneVerified: Bool?
    var isSubscribed: Bool?
    var dailyGoal: Double?
  }
  
  struct Public: Content {
    var name: String?
    var avatar: String?
    var avatarUrls: [String: String]?
  }
  
  // 手机邮箱绑定/更改
  struct BindRequest: Content {
    var identifier: String // 手机号或邮箱
    var code: String // 验证码
    var type: String // phone 或 email
  }
  
  // 设置每日目标
  struct SetDailyGoal: Content {
    var dailyGoal: Double // 目标时长（秒）
  }

  // 用户协议
  struct TermsInfo: Content {
   let currentTermsVersion: String
   let currentPrivacyVersion: String
   let termsUrl: String
   let privacyUrl: String
   let requireNewAgreement: Bool
  }

  // 用户协议同意
  struct TermsAgreement: Content {
    let agreedToTerms: Bool
    let termsVersion: String
  }
  
  // Apple登录请求
  struct AppleSignInRequest: Content {
    let identityToken: String      // Apple身份令牌
    let fullName: String?          // 用户全名（可选）
    let agreedToTerms: Bool        // 是否同意用户协议
  }
}

// MARK: - 数据库迁移
extension User {
  // 添加Apple用户ID字段的迁移
  struct AddAppleUserIDField: AsyncMigration {
    func prepare(on database: Database) async throws {
      try await database.schema(SchemaEnum.users.rawValue)
        .field(FieldKeys.appleUserID, .string)
        .update()
    }
    
    func revert(on database: Database) async throws {
      try await database.schema(SchemaEnum.users.rawValue)
        .deleteField(FieldKeys.appleUserID)
        .update()
    }
  }
}
